package com.otp.webapp.action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.appfuse.model.LabelValue;
import org.appfuse.model.User;
import org.appfuse.util.ConvertUtil;


public class UserList extends BasePage implements Serializable {
	private static final long serialVersionUID = 972359310602744018L;

	private String query;
	private User loggedInUser;
	private List<User> users;

	public void setQuery(String query) {
		this.query = query;
	}

	public String getQuery() {
		return query;
	}

	public UserList() {
		setSortColumn("username");
	}

	public List<User> getUsers() {
		if(users!=null) return users;
		
		List<User> returnedUsers=new ArrayList<User>();

		if (query != null && !"".equals(query.trim())) {
			List<User> usersWithNullFields = userManager.search(query);
			if(users==null) users = new ArrayList<User>();
			else users.clear();
			for(User uwnf:usersWithNullFields) users.add(userManager.getUser(uwnf.getId()+""));
		}
		
		@SuppressWarnings("unchecked")
		List<User> usersSorted = sort(userManager.getUsers());
		users = usersSorted;
		if(users==null) return null;

		if(loggedInUser==null){
			HttpServletRequest request = getRequest();	
			String userName = request.getRemoteUser();
			loggedInUser = userManager.getUserByUsername(userName);	
		}
		if(loggedInUser==null) return null;

		
		//Return user list. Filter by organization if user is not super admin 
		List<LabelValue> roles = loggedInUser.getRoleList();
		if(ConvertUtil.convertListToMap(roles).containsKey("ROLE_SUPER_ADMIN")) return users;
		else{
			String orgName = loggedInUser.getOrgs().getOrganizationName();
			for(User u:users){
				if(u.getOrgs()!=null && orgName.equals(u.getOrgs().getOrganizationName()))
					if(!ConvertUtil.convertListToMap(u.getRoleList()).containsKey("ROLE_SUPER_ADMIN"))
						returnedUsers.add(u);				
			}
			return users=returnedUsers;
		}
	}
	

	public String search() {
		users=null;
		return "success";
	}
}
